package com.hrt.datasender.process.indentity.hj212;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.btcode.log.ILog;
import com.hrt.datasender.datasent.DataSender;
import com.hrt.datasender.process.indentity.IMessageIdentity;
import com.hrt.datasender.process.strategy.hj212.util.CRCUtil;
import com.hrt.datasender.process.strategy.hj212.util.DataIllegalException;

public class MessageIdentityGF implements IMessageIdentity {

    @Override
    public String getProtocolName() {
        return "国发平台";
    }

    @Override
    public List<MessageModel> decode(Object msg) {
        try {
            return parser(msg);
        } 
        catch (DataIllegalException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static List<MessageModel> parser(Object obj) throws DataIllegalException {
        ILog log = DataSender.log;

        String msgStr = obj + "";

        if (msgStr == null || msgStr.equals("")) {
            throw new DataIllegalException("报文为空");
        }

        if (!msgStr.startsWith("##")) {
            throw new DataIllegalException("报文不是以##开头");
        }

        String[] msgs = msgStr.split("\r\n");
        List<MessageModel> models = new ArrayList<>();

        for (int i = 0; i < msgs.length; i++) {
            String msg = msgs[i];
            if (!CRCUtil.match(msg)) {
                log.error("CRC验证不通过", new DataIllegalException("报文：" + msg + "，\r\nCRC验证不通过"));
                continue;
            }
            MessageModel model = new MessageModel();

            String cn = getMetaDataValue(msgStr, "CN");

            model.setCommandId(cn);
            model.setMsg(msgStr);

            models.add(model);
        }
        return models;
    }

    /**
     * 根据参数名称获取元数据值
     *
     * @param msg
     * @param parmName
     * @return
     */
    public static String getMetaDataValue(String msg, String parmName) {
        String regex = parmName + "=(.+?);";
        String result = getMatchedString(regex, msg, 1);
        return result;
    }

    /**
     * 根据正则，获取匹配的部分
     *
     * @param regex
     * @param text
     * @param groupid
     * @return
     */
    private static String getMatchedString(String regex, String text, int groupid) {
        Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);

        Matcher matcher = pattern.matcher(text);

        while (matcher.find()) {
            return matcher.group(groupid);
        }

        return null;
    }

    /**
     * 获取CP命令数据体 gislin 2015年10月29日
     *
     * @param msg
     * @return
     */
    public static String getCP(String msg) {
        String regex = "CP=&&(.+?)&&";
        String result = getMatchedString(regex, msg, 1);
        return result;
    }

}
